let currentPage = 1;
let currentPageSize = 10;
let projectDetails = {};


// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    loadProjects();
    setupEventListeners();
    // 初始化所有tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索框回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchProjects();
        }
    });

    // 状态筛选变化事件
    document.getElementById('statusFilter').addEventListener('change', function() {
        currentPage = 1;
        loadProjects();
    });

    // 排序变化事件
    document.getElementById('sortBy').addEventListener('change', function() {
        currentPage = 1;
        loadProjects();
    });

    document.getElementById('sortOrder').addEventListener('change', function() {
        currentPage = 1;
        loadProjects();
    });

    // 每页显示数量变化事件
    document.getElementById('pageSize').addEventListener('change', function() {
        currentPageSize = parseInt(this.value);
        currentPage = 1;
        loadProjects();
    });
}

// 加载项目列表
function loadProjects() {
    const search = document.getElementById('searchInput').value;
    const status = document.getElementById('statusFilter').value;
    const sortBy = document.getElementById('sortBy').value;
    const sortOrder = document.getElementById('sortOrder').value;
    const startTime = document.getElementById('startTime')?.value;
    const endTime = document.getElementById('endTime')?.value;

    let url = `/api/projects/get_project/?page=${currentPage}&page_size=${currentPageSize}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    if (status) url += `&project_status=${status}`;
    if (sortBy) url += `&sort_by=${sortBy}`;
    if (sortOrder) url += `&sort_order=${sortOrder}`;
    if (startTime) url += `&start_time=${encodeURIComponent(startTime)}`;
    if (endTime) url += `&end_time=${encodeURIComponent(endTime)}`;

    axios.get(url)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                // 加载每个项目的子计划
                const projects = data.data.projects;
                const loadSubPlansPromises = projects.map(project => 
                    axios.get(`/api/projects/get_sub_plan/?project_id=${project.project_id}`)
                        .then(response => {
                            if (response.data.code === 0) {
                                project.sub_plans = response.data.data;
                            }
                            return project;
                        })
                        .catch(() => {
                            project.sub_plans = [];
                            return project;
                        })
                );

                Promise.all(loadSubPlansPromises)
                    .then(projectsWithSubPlans => {
                        renderProjectTable(projectsWithSubPlans);
                        renderPagination(data.data.pagination);
                    });
            } else {
                showToast('获取项目列表失败', 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
}

// 渲染项目表格
function renderProjectTable(projects) {
    const tbody = document.getElementById('projectTableBody');
    tbody.innerHTML = '';
    projectDetails = {};

    projects.forEach(project => {
        projectDetails[project.project_id] = project;
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>
                <div class="d-flex align-items-center">
                    <div class="avatar avatar-sm me-2">
                        <span class="avatar-initial rounded-circle bg-label-primary">
                            ${project.project_name.charAt(0).toUpperCase()}
                        </span>
                    </div>
                    <div class="fw-medium">${project.project_name}</div>
                </div>
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <div class="avatar avatar-sm me-2">
                        <span class="avatar-initial rounded-circle bg-label-info">
                            ${project.project_leader.user_name.charAt(0).toUpperCase()}
                        </span>
                    </div>
                    <div>${project.project_leader.user_name}</div>
                </div>
            </td>
            <td>
                <span class="project-status status-${project.project_status.id}">
                    ${project.project_status.name}
                </span>
            </td>
            <td>${project.create_time}</td>
            <td>${project.update_time}</td>
            <td>
                <div class="dropdown">
                    <button class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                        <i class='bx bx-dots-vertical-rounded'></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item" href="javascript:void(0);" onclick="viewProject('${project.project_id}')">
                                <i class='bx bx-show me-2'></i>查看
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="javascript:void(0);" onclick="showEditProjectModal('${project.project_id}')">
                                <i class='bx bx-edit me-2'></i>编辑
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="javascript:void(0);" onclick="showAddPrototypeModal('${project.project_id}')">
                                <i class='bx bx-image-add me-2'></i>添加原型图
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="javascript:void(0);" onclick="showAddProjectLeaderModal('${project.project_id}')">
                                <i class='bx bx-user-plus me-2'></i>添加负责人
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteProject('${project.project_id}')">
                                <i class='bx bx-trash me-2'></i>删除
                            </a>
                        </li>
                    </ul>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 渲染分页
function renderPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    paginationElement.innerHTML = '';

    // 上一页
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage - 1})">
            <i class='bx bx-chevron-left'></i>
        </a>
    `;
    paginationElement.appendChild(prevLi);

    // 页码
    for (let i = 1; i <= pagination.total_pages; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${currentPage === i ? 'active' : ''}`;
        li.innerHTML = `
            <a class="page-link" href="javascript:void(0);" onclick="changePage(${i})">${i}</a>
        `;
        paginationElement.appendChild(li);
    }

    // 下一页
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === pagination.total_pages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage + 1})">
            <i class='bx bx-chevron-right'></i>
        </a>
    `;
    paginationElement.appendChild(nextLi);
}

// 切换页码
function changePage(page) {
    currentPage = page;
    loadProjects();
}

// 搜索项目
function searchProjects() {
    currentPage = 1;
    loadProjects();
}

// 添加项目
function addProject() {
    const form = document.getElementById('addProjectForm');
    const formData = new FormData(form);
    
    // 将FormData转换为URLSearchParams
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }

    axios.post('/api/projects/create_project/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('添加成功', 'success');
            $('#addProjectModal').modal('hide');
            form.reset();
            loadProjects();
        } else {
            showToast(data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
    });
}

// 显示添加原型图模态框
function showAddPrototypeModal(projectId) {
    document.getElementById('prototypeProjectId').value = projectId;
    const modal = new bootstrap.Modal(document.getElementById('addPrototypeModal'));
    modal.show();
}

// 添加原型图
function addPrototype() {
    const form = document.getElementById('addPrototypeForm');
    const formData = new FormData(form);

    axios.post('/api/projects/add_project_prototype/', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('添加成功', 'success');
            $('#addPrototypeModal').modal('hide');
            form.reset();
            loadProjects();
        } else {
            showToast(data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
    });
}

// 修改项目详情模态框，添加原型图展示部分
function viewProject(projectId) {
    const project = projectDetails[projectId];
    if (!project) {
        showToast('获取项目信息失败', 'error');
        return;
    }

    // 创建并显示项目详情模态框
    const modalHtml = `
        <div class="modal fade" id="viewProjectModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">项目详情</h5>
                        <div class="d-flex align-items-center gap-2">
                            <button type="button" class="btn btn-outline-info btn-sm" id="getLeaderBtn">
                                <i class='bx bx-user'></i> 获取负责人
                            </button>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                    </div>
                    <div class="modal-body p-0">
                        <div class="row g-0">
                            <!-- 左侧项目信息 -->
                            <div class="col-md-6 border-end">
                                <div class="p-4">
                                    <div class="d-flex align-items-center mb-4">
                                        <div class="avatar avatar-lg me-3">
                                            <span class="avatar-initial rounded-circle bg-label-primary">
                                                ${project.project_name.charAt(0).toUpperCase()}
                                            </span>
                                        </div>
                                        <div>
                                            <h5 class="mb-1">${project.project_name}</h5>
                                            <span class="text-muted">项目ID: ${project.project_id}</span>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-12 mb-3">
                                            <small class="text-muted d-block">项目描述</small>
                                            <p class="mb-0">${project.project_description || '暂无描述'}</p>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">项目状态</small>
                                            <span class="project-status status-${project.project_status.id}">
                                                ${project.project_status.name}
                                            </span>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">项目文档</small>
                                            <a href="${project.project_doc_url}" target="_blank" class="text-primary">
                                                ${project.project_doc_url || '暂无文档'}
                                            </a>
                                        </div>
                                        <div class="col-12 mb-3">
                                            <small class="text-muted d-block">项目负责人</small>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar avatar-sm me-2">
                                                    <span class="avatar-initial rounded-circle bg-label-info">
                                                        ${project.project_leader.user_name.charAt(0).toUpperCase()}
                                                    </span>
                                                </div>
                                                <div>
                                                    <div class="fw-medium">${project.project_leader.user_name}</div>
                                                    <small class="text-muted">${project.project_leader.account}</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">创建时间</small>
                                            <span class="fw-medium">${project.create_time}</span>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">更新时间</small>
                                            <span class="fw-medium">${project.update_time}</span>
                                        </div>
                                    </div>
                                    <!-- 在左侧项目信息区添加 -->
                                    ${project.prototypes && project.prototypes.length > 0 ? `
                                        <div class="mt-4">
                                            <small class="text-muted d-block mb-2">项目原型图</small>
                                            <div class="row g-2">
                                                ${project.prototypes.map(proto => `
                                                    <div class="col-4">
                                                        <div class="card h-100 cursor-pointer" onclick="showPrototypeCarousel('${project.project_id}', '${proto.prototype_id}')">
                                                            <img src="${proto.prototype_url}" class="card-img-top object-fit-cover" style="height:100px;" alt="${proto.prototype_name}">
                                                            <div class="card-body p-2">
                                                                <div class="fw-medium text-truncate" title="${proto.prototype_name}">${proto.prototype_name}</div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                `).join('')}
                                            </div>
                                        </div>
                                    ` : ''}
                                    <!-- 负责人信息展示区 -->
                                    <div id="projectLeaderInfo" class="mt-4"></div>
                                </div>
                            </div>

                            <!-- 右侧子计划列表 -->
                            <div class="col-md-6">
                                <div class="p-4">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="mb-0">子计划列表</h6>
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-sm btn-outline-secondary" onclick="refreshSubPlans('${project.project_id}')" data-bs-toggle="tooltip" data-bs-placement="top" title="刷新子计划列表">
                                                <i class='bx bx-refresh'></i>
                                            </button>
                                            <button class="btn btn-sm btn-primary" onclick="showAddSubPlanModal('${project.project_id}')">
                                                <i class='bx bx-plus me-1'></i>添加子计划
                                            </button>
                                        </div>
                                    </div>
                                    <div class="sub-plan-list-container">
                                        <table class="table table-hover sub-plan-table">
                                            <thead>
                                                <tr>
                                                    <th>子计划名称</th>
                                                    <th>负责人</th>
                                                    <th>状态</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${project.sub_plans ? project.sub_plans.map(plan => `
                                                    <tr>
                                                        <td>
                                                            <div class="fw-medium">${plan.sub_plan_name}</div>
                                                            <small class="text-muted">${plan.sub_plan_description || '暂无描述'}</small>
                                                        </td>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar avatar-sm me-2">
                                                                    <span class="avatar-initial rounded-circle bg-label-info">
                                                                        ${plan.sub_plan_total_leader.user_name.charAt(0).toUpperCase()}
                                                                    </span>
                                                                </div>
                                                                <div>${plan.sub_plan_total_leader.user_name}</div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <span class="status-icon status-icon-${plan.sub_plan_status.id}" 
                                                                  data-bs-toggle="tooltip" 
                                                                  data-bs-placement="top" 
                                                                  title="${plan.sub_plan_status.name}">
                                                                ${plan.sub_plan_status.id === 1 ? '<i class="bx bx-time"></i>' :
                                                                  plan.sub_plan_status.id === 2 ? '<i class="bx bx-loader-alt"></i>' :
                                                                  plan.sub_plan_status.id === 3 ? '<i class="bx bx-check-circle"></i>' :
                                                                  plan.sub_plan_status.id === 4 ? '<i class="bx bx-x-circle"></i>' :
                                                                  '<i class="bx bx-pause-circle"></i>'}
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                                                                    <i class='bx bx-dots-vertical-rounded'></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li>
                                                                        <a class="dropdown-item" href="javascript:void(0);" onclick="viewSubPlan('${plan.sub_plan_id}')">
                                                                            <i class='bx bx-show me-2'></i>查看
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item" href="javascript:void(0);" onclick="editSubPlan('${plan.sub_plan_id}')">
                                                                            <i class='bx bx-edit me-2'></i>编辑
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteSubPlan('${plan.sub_plan_id}')">
                                                                            <i class='bx bx-trash me-2'></i>删除
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                `).join('') : '<tr><td colspan="4" class="text-center">暂无子计划</td></tr>'}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 移除可能存在的旧模态框
    const oldModal = document.getElementById('viewProjectModal');
    if (oldModal) {
        oldModal.remove();
    }

    // 添加新模态框到页面
    const modalContainer = document.createElement('div');
    modalContainer.innerHTML = modalHtml;
    document.body.appendChild(modalContainer);

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('viewProjectModal'));
    modal.show();

    // 初始化模态框中的tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 监听模态框关闭事件，移除DOM
    document.getElementById('viewProjectModal').addEventListener('hidden.bs.modal', function () {
        this.remove();
    });

    // 绑定获取负责人按钮事件
    document.getElementById('getLeaderBtn').onclick = function() {
        getProjectLeader(project.project_id);
    };
}

// 新增：获取项目负责人并展示
function getProjectLeader(projectId) {
    const leaderInfoDiv = document.getElementById('projectLeaderInfo');
    leaderInfoDiv.innerHTML = `<div class='text-center text-secondary py-3'><i class='bx bx-loader-alt bx-spin'></i> 正在获取负责人...</div>`;
    axios.get(`/api/projects/ProjectLeader/get_project_leader/?project_id=${projectId}`)
        .then(response => {
            const data = response.data;
            if (data.code === 0 && Array.isArray(data.data) && data.data.length > 0) {
                leaderInfoDiv.innerHTML = data.data.map(leader => `
                    <div class="card mb-2">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="avatar avatar-md">
                                <span class="avatar-initial rounded-circle bg-label-info">
                                    ${leader.leader_user.user_name.charAt(0).toUpperCase()}
                                </span>
                            </div>
                            <div class="flex-grow-1">
                                <div class="fw-bold">${leader.leader_user.user_name} <span class="badge bg-label-primary ms-2">负责人</span></div>
                                <div class="text-muted small">账号：${leader.leader_user.account}</div>
                                <div class="text-muted small">备注：${leader.leader_remark || '无'}</div>
                                <div class="text-muted small">负责子计划：${leader.sub_plan_project ? leader.sub_plan_project.sub_plan_name : '无'}</div>
                            </div>
                            <div class="text-end">
                                <div class="text-muted small">创建：${leader.create_time}</div>
                                <div class="text-muted small">更新：${leader.update_time}</div>
                            </div>
                        </div>
                    </div>
                `).join('');
            } else {
                leaderInfoDiv.innerHTML = `<div class='text-center text-muted py-3'>暂无负责人信息</div>`;
            }
        })
        .catch(error => {
            leaderInfoDiv.innerHTML = `<div class='text-center text-danger py-3'>获取负责人失败</div>`;
        });
}

// 显示编辑项目模态框
function showEditProjectModal(projectId) {
    const project = projectDetails[projectId];
    if (!project) {
        showToast('获取项目信息失败', 'error');
        return;
    }

    // 填充表单数据
    document.getElementById('editProjectId').value = project.project_id;
    document.getElementById('editProjectName').value = project.project_name;
    document.getElementById('editProjectDescription').value = project.project_description || '';
    document.getElementById('editProjectDocUrl').value = project.project_doc_url || '';
    document.getElementById('editProjectStatus').value = project.project_status.id;

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('editProjectModal'));
    modal.show();
}

// 更新项目
function updateProject() {
    const form = document.getElementById('editProjectForm');
    const formData = new FormData(form);
    
    // 将FormData转换为URLSearchParams
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }

    axios.post('/api/projects/update_project/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('更新成功', 'success');
            $('#editProjectModal').modal('hide');
            loadProjects();
        } else {
            showToast(data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
    });
}

// 删除项目
function deleteProject(projectId) {
    showConfirm({
        title: '确认删除',
        message: '确定要删除这个项目吗？此操作不可恢复。',
        confirmText: '删除',
        cancelText: '取消',
        type: 'danger'
    }).then(() => {
        const params = new URLSearchParams();
        params.append('project_id', projectId);

        axios.post('/api/projects/delete_project/', params, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                showToast('删除成功', 'success');
                loadProjects();
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
    }).catch(() => {
        // 用户取消删除，不做任何操作
    });
}

// 显示原型图轮播
function showPrototypeCarousel(projectId, prototypeId) {
    const project = projectDetails[projectId];
    if (!project || !project.prototypes || project.prototypes.length === 0) {
        return;
    }

    const carouselInner = document.querySelector('#prototypeCarousel .carousel-inner');
    carouselInner.innerHTML = '';

    project.prototypes.forEach((prototype, index) => {
        const div = document.createElement('div');
        div.className = `carousel-item ${prototype.prototype_id === prototypeId ? 'active' : ''}`;
        div.innerHTML = `
            <div class="d-flex justify-content-center align-items-center" style="height: 80vh;">
                <img src="${prototype.prototype_url}" class="img-fluid" alt="${prototype.prototype_name}">
            </div>
            <div class="position-absolute bottom-0 start-0 end-0 bg-dark bg-opacity-50 text-white p-3">
                <h5 class="mb-1">${prototype.prototype_name}</h5>
                <p class="mb-0 small">${prototype.prototype_description || '暂无描述'}</p>
            </div>
        `;
        carouselInner.appendChild(div);
    });

    const modal = new bootstrap.Modal(document.getElementById('prototypeCarouselModal'));
    modal.show();
}

// 监听轮播模态框关闭事件
document.getElementById('prototypeCarouselModal').addEventListener('hidden.bs.modal', function () {
    const carousel = document.getElementById('prototypeCarousel');
    const bsCarousel = bootstrap.Carousel.getInstance(carousel);
    if (bsCarousel) {
        bsCarousel.dispose();
    }
});

// 删除原型图
function deletePrototype(prototypeId) {
    showConfirm({
        title: '确认删除',
        message: '确定要删除这个原型图吗？此操作不可恢复。',
        confirmText: '删除',
        cancelText: '取消',
        type: 'danger'
    }).then(() => {
        const params = new URLSearchParams();
        params.append('prototype_id', prototypeId);

        axios.post('/api/projects/delete_project_prototype/', params, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                showToast('删除成功', 'success');
                // 关闭轮播模态框（如果打开的话）
                const carouselModal = document.getElementById('prototypeCarouselModal');
                if (carouselModal) {
                    const modal = bootstrap.Modal.getInstance(carouselModal);
                    if (modal) {
                        modal.hide();
                    }
                }
                // 重新加载项目列表
                loadProjects();
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
    }).catch(() => {
        // 用户取消删除，不做任何操作
    });
}

// 显示添加子计划模态框
function showAddSubPlanModal(projectId) {
    document.getElementById('subPlanProjectId').value = projectId;
    const modal = new bootstrap.Modal(document.getElementById('addSubPlanModal'));
    modal.show();
}

// 创建子计划
function createSubPlan() {
    const form = document.getElementById('addSubPlanForm');
    const formData = new FormData(form);
    
    // 将FormData转换为URLSearchParams
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }

    axios.post('/api/projects/create_sub_plan/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('创建成功', 'success');
            $('#addSubPlanModal').modal('hide');
            form.reset();
            loadProjects();
        } else {
            showToast(data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
    });
}

// 查看子计划
function viewSubPlan(subPlanId) {
    axios.get(`/api/projects/get_sub_plan/?sub_plan_id=${subPlanId}`)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                const subPlan = data.data;
                // 创建并显示子计划详情模态框
                const modalHtml = `
                    <div class="modal fade" id="viewSubPlanModal" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">子计划详情</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="d-flex align-items-center mb-4">
                                        <div class="avatar avatar-lg me-3">
                                            <span class="avatar-initial rounded-circle bg-label-primary">
                                                ${subPlan.sub_plan_name.charAt(0).toUpperCase()}
                                            </span>
                                        </div>
                                        <div>
                                            <h5 class="mb-1">${subPlan.sub_plan_name}</h5>
                                            <span class="text-muted">子计划ID: ${subPlan.sub_plan_id}</span>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-12 mb-3">
                                            <small class="text-muted d-block">子计划描述</small>
                                            <p class="mb-0">${subPlan.sub_plan_description || '暂无描述'}</p>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">子计划状态</small>
                                            <span class="project-status status-${subPlan.sub_plan_status.id}">
                                                ${subPlan.sub_plan_status.name}
                                            </span>
                                        </div>
                                        <div class="col-12 mb-3">
                                            <small class="text-muted d-block">负责人</small>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar avatar-sm me-2">
                                                    <span class="avatar-initial rounded-circle bg-label-info">
                                                        ${subPlan.sub_plan_total_leader.user_name.charAt(0).toUpperCase()}
                                                    </span>
                                                </div>
                                                <div>
                                                    <div class="fw-medium">${subPlan.sub_plan_total_leader.user_name}</div>
                                                    <small class="text-muted">${subPlan.sub_plan_total_leader.account}</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">创建时间</small>
                                            <span class="fw-medium">${subPlan.create_time}</span>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <small class="text-muted d-block">更新时间</small>
                                            <span class="fw-medium">${subPlan.update_time}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;

                // 移除可能存在的旧模态框
                const oldModal = document.getElementById('viewSubPlanModal');
                if (oldModal) {
                    oldModal.remove();
                }

                // 添加新模态框到页面
                const modalContainer = document.createElement('div');
                modalContainer.innerHTML = modalHtml;
                document.body.appendChild(modalContainer);

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('viewSubPlanModal'));
                modal.show();

                // 监听模态框关闭事件，移除DOM
                document.getElementById('viewSubPlanModal').addEventListener('hidden.bs.modal', function () {
                    this.remove();
                });
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
}

// 编辑子计划
function editSubPlan(subPlanId) {
    // 获取子计划数据
    axios.get(`/api/projects/get_sub_plan/?sub_plan_id=${subPlanId}`)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                const subPlan = data.data;
                
                // 填充表单数据
                document.getElementById('editSubPlanId').value = subPlan.sub_plan_id;
                document.getElementById('editSubPlanProjectId').value = subPlan.project.project_id;
                document.getElementById('editSubPlanName').value = subPlan.sub_plan_name;
                document.getElementById('editSubPlanDescription').value = subPlan.sub_plan_description || '';
                document.getElementById('editSubPlanStatus').value = subPlan.sub_plan_status.id;

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('editSubPlanModal'));
                modal.show();
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
}

// 添加更新子计划函数
function updateSubPlan() {
    const form = document.getElementById('editSubPlanForm');
    const formData = new FormData(form);
    
    // 将FormData转换为URLSearchParams
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }

    axios.post('/api/projects/update_sub_plan/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('更新成功', 'success');
            $('#editSubPlanModal').modal('hide');
            // 刷新子计划列表
            refreshSubPlans(params.get('project'));
        } else {
            showToast(data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
    });
}

// 添加刷新子计划列表的函数
function refreshSubPlans(projectId) {
    const project = projectDetails[projectId];
    if (!project) {
        showToast('获取项目信息失败', 'error');
        return;
    }

    // 显示加载动画
    const refreshBtn = event.currentTarget;
    const originalHtml = refreshBtn.innerHTML;
    refreshBtn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i>';
    refreshBtn.disabled = true;

    // 重新加载子计划数据
    axios.get(`/api/projects/get_sub_plan/?project_id=${projectId}`)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                project.sub_plans = data.data;
                // 更新子计划列表显示
                const subPlanTableBody = document.querySelector('#viewProjectModal .table tbody');
                if (subPlanTableBody) {
                    subPlanTableBody.innerHTML = project.sub_plans.map(plan => `
                        <tr>
                            <td>
                                <div class="fw-medium">${plan.sub_plan_name}</div>
                                <small class="text-muted">${plan.sub_plan_description || '暂无描述'}</small>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar avatar-sm me-2">
                                        <span class="avatar-initial rounded-circle bg-label-info">
                                            ${plan.sub_plan_total_leader.user_name.charAt(0).toUpperCase()}
                                        </span>
                                    </div>
                                    <div>${plan.sub_plan_total_leader.user_name}</div>
                                </div>
                            </td>
                            <td>
                                <span class="status-icon status-icon-${plan.sub_plan_status.id}" 
                                      data-bs-toggle="tooltip" 
                                      data-bs-placement="top" 
                                      title="${plan.sub_plan_status.name}">
                                    ${plan.sub_plan_status.id === 1 ? '<i class="bx bx-time"></i>' :
                                      plan.sub_plan_status.id === 2 ? '<i class="bx bx-loader-alt"></i>' :
                                      plan.sub_plan_status.id === 3 ? '<i class="bx bx-check-circle"></i>' :
                                      plan.sub_plan_status.id === 4 ? '<i class="bx bx-x-circle"></i>' :
                                      '<i class="bx bx-pause-circle"></i>'}
                                </span>
                            </td>
                            <td>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                                        <i class='bx bx-dots-vertical-rounded'></i>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a class="dropdown-item" href="javascript:void(0);" onclick="viewSubPlan('${plan.sub_plan_id}')">
                                                <i class='bx bx-show me-2'></i>查看
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="javascript:void(0);" onclick="editSubPlan('${plan.sub_plan_id}')">
                                                <i class='bx bx-edit me-2'></i>编辑
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteSubPlan('${plan.sub_plan_id}')">
                                                <i class='bx bx-trash me-2'></i>删除
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </td>
                        </tr>
                    `).join('') || '<tr><td colspan="4" class="text-center">暂无子计划</td></tr>';

                    // 重新初始化tooltips
                    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                    tooltipTriggerList.map(function (tooltipTriggerEl) {
                        return new bootstrap.Tooltip(tooltipTriggerEl);
                    });
                }
                showToast('刷新成功', 'success');
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        })
        .finally(() => {
            // 恢复按钮状态
            refreshBtn.innerHTML = originalHtml;
            refreshBtn.disabled = false;
        });
}

// 删除子计划
function deleteSubPlan(subPlanId) {
    showConfirm({
        title: '确认删除',
        message: '确定要删除这个子计划吗？此操作不可恢复。',
        confirmText: '删除',
        cancelText: '取消',
        type: 'danger'
    }).then(() => {
        const params = new URLSearchParams();
        params.append('sub_plan_id', subPlanId);

        axios.post('/api/projects/delete_sub_plan/', params, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                showToast('删除成功', 'success');
                // 获取当前项目ID并刷新子计划列表
                const projectId = document.querySelector('#viewProjectModal .sub-plan-list-container').closest('.col-md-6').querySelector('.btn-primary').getAttribute('onclick').match(/'([^']+)'/)[1];
                refreshSubPlans(projectId);
            } else {
                showToast(data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('系统错误', 'error');
        });
    }).catch(() => {
        // 用户取消删除，不做任何操作
    });
}

// 添加项目负责人相关函数
function showAddProjectLeaderModal(projectId) {
    // 重置进度
    document.getElementById('step1').classList.remove('completed');
    document.getElementById('step2').classList.remove('active', 'completed');
    document.getElementById('step3').classList.remove('active', 'completed');
    
    // 清空并禁用子计划选择
    document.getElementById('subPlanSelect').innerHTML = '<option value="">请先选择项目</option>';
    document.getElementById('subPlanSelect').disabled = true;
    // 重置隐藏字段
    document.getElementById('leaderProjectId').value = '';
    
    // 加载项目列表
    axios.get('/api/projects/get_project/')
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                const projectSelect = document.getElementById('projectSelect');
                projectSelect.innerHTML = '<option value="">请选择项目</option>';
                data.data.projects.forEach(project => {
                    const option = document.createElement('option');
                    option.value = project.project_id;
                    option.textContent = project.project_name;
                    // 不再自动选中第一个项目
                    if (project.project_id === projectId) {
                        option.selected = true;
                        // 同步隐藏字段
                        document.getElementById('leaderProjectId').value = projectId;
                        loadSubPlansForLeader();
                    }
                    projectSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            showToast('获取项目列表失败', 'error');
        });

    // 监听项目选择变化，动态同步隐藏字段
    setTimeout(() => {
        const projectSelect = document.getElementById('projectSelect');
        if (projectSelect) {
            projectSelect.onchange = function() {
                document.getElementById('leaderProjectId').value = this.value;
                loadSubPlansForLeader();
            };
        }
        // 监听子计划选择变化，动态更新进度
        const subPlanSelect = document.getElementById('subPlanSelect');
        if (subPlanSelect) {
            subPlanSelect.onchange = function() {
                const subPlanId = this.value;
                if (subPlanId) {
                    document.getElementById('step2').classList.add('completed');
                    document.getElementById('step3').classList.add('active');
                } else {
                    document.getElementById('step2').classList.remove('completed');
                    document.getElementById('step3').classList.remove('active');
                }
            };
        }
    }, 300);

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('addProjectLeaderModal'));
    modal.show();
}

function loadSubPlansForLeader() {
    const projectId = document.getElementById('projectSelect').value;
    const subPlanSelect = document.getElementById('subPlanSelect');
    
    if (!projectId) {
        subPlanSelect.innerHTML = '<option value="">请先选择项目</option>';
        subPlanSelect.disabled = true;
        // 重置进度
        document.getElementById('step1').classList.remove('completed');
        document.getElementById('step2').classList.remove('active', 'completed');
        document.getElementById('step3').classList.remove('active', 'completed');
        return;
    }

    // 更新进度
    document.getElementById('step1').classList.add('completed');
    document.getElementById('step2').classList.add('active');

    // 加载子计划列表
    axios.get(`/api/projects/get_sub_plan/?project_id=${projectId}`)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                subPlanSelect.innerHTML = '<option value="">请选择子计划</option>';
                data.data.forEach(subPlan => {
                    const option = document.createElement('option');
                    option.value = subPlan.sub_plan_id;
                    option.textContent = subPlan.sub_plan_name;
                    subPlanSelect.appendChild(option);
                });
                subPlanSelect.disabled = false;
            }
        })
        .catch(error => {
            showToast('获取子计划列表失败', 'error');
        });
}

function addProjectLeader() {
    const form = document.getElementById('addProjectLeaderForm');
    const formData = new FormData(form);
    
    // 获取当前用户ID
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user || !user.user_id) {
        showToast('获取用户信息失败', 'error');
        return;
    }

    // 将FormData转换为URLSearchParams
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }
    params.append('leader_user', user.user_id);

    // 验证必填字段
    if (!params.get('project') || !params.get('sub_plan_project')) {
        showToast('请选择项目和子计划', 'error');
        return;
    }

    // 更新进度
    document.getElementById('step2').classList.add('completed');
    document.getElementById('step3').classList.add('active');

    axios.post('/api/projects/ProjectLeader/add_project_leader/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('添加成功', 'success');
            $('#addProjectLeaderModal').modal('hide');
            form.reset();
            // 重置进度
            document.getElementById('step1').classList.remove('completed');
            document.getElementById('step2').classList.remove('active', 'completed');
            document.getElementById('step3').classList.remove('active', 'completed');
            // 刷新项目列表
            loadProjects();
        } else {
            showToast(data.msg, 'error');
            // 重置进度
            document.getElementById('step3').classList.remove('active');
        }
    })
    .catch(error => {
        showToast('系统错误', 'error');
        // 重置进度
        document.getElementById('step3').classList.remove('active');
    });
}